<?php

namespace api\modules\v1\models;

use api\func\func;
use Yii;
use api\common\models\Common;
use yii\base\Exception;
use yii\web\NotFoundHttpException;
use yii\web\HttpException;
use yii\data\ActiveDataProvider;
use api\modules\v1\models\News;
use api\modules\v1\models\Like;
use api\common\controllers\CommonController;
use api\common\models\Mar;
use yii\db\Expression;
use yii\helpers\Url;
use yii\data\Pagination;
use yii\web\Link;
use \yii\caching\FileDependency;

class Comment extends Common
{


    public $syn_top;

    /**
     * @return array|string
     */
    public static function tableName()
    {
        return '{{%comment_app}}';
    }


    public function rules()
    {
        return [
            ['content_id', 'required','message'=>'内容ID不能为空'],
            ['content_id', 'integer'],

            ['catid', 'required','message'=>'分类ID不能为空'],
            ['catid', 'integer'],

            ['top_pid', 'default','value'=>'0'],
            ['top_pid', 'integer'],

            ['time','default','value'=>null],

            ['content', 'required','message'=>'评论内容不能为空'],
            ['content', 'string', 'min' => 2,  'max' => 500],
            ['content','match','pattern'=>'/^[\x{4e00}-\x{9fa5}A-Za-z0-9,.?!;":\'。，；：？！《》“”‘’、（）……——]{1,}$/u','when' =>function($model) {
                return $model->time == null;
            },
'message'=>'您输入的文字是非法字符'],

            ['content_id', 'validateContent_id'],

            ['content', 'validateContent'],

            ['pid', 'required','message'=>'回复评论ID不能为空'],
            ['pid', 'integer'],
            ['pid', 'validatePid'],

            ['syn_top', 'default','value'=>'0'],
            ['syn_top', 'integer'],

        ];
    }

    public function attributeLabels()
    {
        return [
            'content_id' => Yii::t('app', '内容ID'),
            'catid' => Yii::t('app', '分类'),
            'content' => Yii::t('app', '评论内容'),
            'pid' => Yii::t('app', '回复评论ID')
        ];
    }

    /*
     * 验证上级留言是否存在
     * @param $attribute
     * @param $params
     * @return bool
     */
    public function validatePid($attribute, $params)
    {
        if($this->pid !=0 && !$this->findOne(['comment_id'=>$this->pid])){
            $this->addError($attribute, '未找到上级信息pid');
        }
        return true;
    }

    /*
     * 验证文章内容
     * @param $attribute
     * @param $params
     */
    public function validateContent($attribute, $params){
        if(preg_match ('/select|inert|update|delete|\/\*|UNION|into|load_file|outfile/', $this->content )){
            throw new HttpException(401,'请勿提交非法参数',0);
        }
        $this->content= func::safe_filter($this->content);

        if($this->time == null || $this->time == 'undefind'){ //如果不存在post时间 则取系统默认时间
            $this->time = date('Y-m-d H:i:s');
        }

        return true;
    }

    /*
     * 验证文章是否存在
     * @param $attribute
     * @param $params
     * @return bool
     */

    public function validateContent_id($attribute, $params)
    {
        $news_table = '{{%'.News::getTable($this->catid).'}}';
        $news_model = new Mar($news_table);
        if(!$news_model->findOnex($news_table,['id'=>$this->content_id])){
            $this->addError($attribute, '未找到文章信息content_id');
        }

        //敏感词过滤
        $cahce = Yii::$app->cache;
        $cacheKey = 'comment_badword';
        $badword = $cahce->get($cacheKey);
        if ($badword === false) {
            $badword_model = new Mar('{{%badword}}');
            $badword = $badword_model->find()->where('use_range != 1')->asArray()->all();
            $cahce->set($cacheKey, $badword,Yii::$app->params['cache_time_comment_badword'],new FileDependency(['fileName' => 'cache.txt']));
        }

        foreach($badword as $value){
/*            if(strpos($this->content,$value['badword']) !== false){
                throw new HttpException(401,'你的评论内容带有敏感信息,评论失败!',0);
            }*/
            if($value['use_range'] != 1) {
                $this->content = str_replace(trim($value['badword']), $value['replaceword'] == '' ? str_pad('*', mb_strlen($value['badword'], 'UTF-8'), '*') : $value['replaceword'], $this->content);
            }
        }
        return true;
    }

    /*
     * 评论提交
     * @return bool
     * @throws NotFoundHttpException
     */
    public function pl(){
        if ($this->validate()) {
            $news_table = '{{%'.News::getTable($this->catid).'}}';
            //$news = new Mar($news_table);
            if($this->pid != 0){ //针对评论进行评论
                //self::updateAll(['comment' => new Expression('`comment` + 1')], ['comment_id' => $this->pid]);

                $uid = self::findOne(['comment_id' => $this->pid]);
                $msg = new Msg();
                $msg->take_uid = $uid->uid;
                $msg->send_uid = Yii::$app->user->identity->id;
                $msg->message = '您的“'.$uid->content.'”评论有新的回复';
                $msg->type = 2;
                $msg->url = Url::to(['comment/list','content_id' => $this->content_id,'catid' => $this->catid,'pid' => $this->pid], false);
                $msg->time = date('Y-m-d H:i:s');
                $msg->isread = 0;
                $msg->insert();

            }else{ //针对文章进行评论
                //$news->updateAll(['comment' => new Expression('`comment` + 1')], ['id' => $this->content_id]);
            }

            $this->uid = Yii::$app->user->identity->id;
            $this->username = Yii::$app->user->identity->nickname !='' ? Yii::$app->user->identity->nickname : Yii::$app->user->identity->phone;
            if ($this->save(false)) {
                if($this->syn_top == '1' && $this->pid !='0'){ //同时评论到文章
                    $this->setAttributes(['top_pid'=>'0','pid'=>'0']);
                    unset($this->comment_id);
                    $this->isNewRecord = true;
                    $this->save(false);
                }
                return true;
            }
        }
        return null;
    }

    /*
     * 删除评论
     * @param $comment_id
     * @return bool
     * @throws HttpException
     */
    public function del($comment_id){
        if($data = $this->find()->select('*')->where(['comment_id'=>$comment_id])->one()){
            if($data['uid'] != Yii::$app->user->identity->id){
                throw new HttpException(401,'请勿非法传递参数!',0);
            }

            if($this->deleteAll(['comment_id'=>$comment_id,'uid'=>Yii::$app->user->identity->id])){

                /**
                $news_table = '{{%'.News::getTable($data['catid']).'}}';
                $news = new Mar($news_table);
                $news->updateAll(['comment' => new Expression('`comment` - 1')], ['id' => $data['content_id']]);
                $comment_ids = array_unique([$data->top_pid,$data->pid]);
                foreach($comment_ids as $value){
                    Comment::updateAll(['comment' => new Expression('`comment` - 1')], ['comment_id' => $value]);
                }
                **/
                return true;
            }else{
                return false;
            }
        }else{
            throw new HttpException(401,'该评论不存在!',0);
        }
    }




    /*
     * 获取评论列表
     * @param $id
     * @param $catid
     * @param $pid 上级id
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getList($content_id,$catid,$pid){
        Like::$_tableName = Like::tableExists(Like::formatTable($content_id,Yii::$app->params['table_like']['num'],Yii::$app->params['table_like']['table']));

        $query =(new \yii\db\Query());
        $query->from(self::tableName().' as a');
        $query->select('a.*,b.head_img,b.username,b.nickname,b.phone');
        $query->innerJoin('{{%user_app}} as b','a.uid = b.id');
        if($pid == 0){
            $where = 'a.`status` =1 and a.content_id='.$content_id.' and a.catid='.$catid.' and (a.pid=0 and top_pid = 0)';
        }else{
            $where = 'a.`status` =1 and a.content_id='.$content_id.' and a.catid='.$catid.' and (a.pid='.$pid.')';
        }
        $query->where($where);
        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->defaultPageSize = Yii::$app->params['page_size'];
        $data = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->orderBy('a.time '.($pid != 0 ? 'desc' : 'desc'))
            ->all();

        $this->serializePagination($pagination);
        $pagination->defaultPageSize = Yii::$app->params['page_size'];
        $parent=[];

        $_child_data = [];
        if($pid !=0){
            $query =(new \yii\db\Query());
            $_child = $query->from(self::tableName().' as a')->select('a.*,b.head_img,b.username,b.nickname,b.phone')->innerJoin('{{%user_app}} as b','a.uid = b.id')->where('a.`status` =1 and a.content_id='.$content_id.' and a.catid='.$catid.' and (a.pid='.$pid.' or top_pid = '.$pid.')')->orderBy('a.time desc')->all();
            foreach($_child as $key=>$value){
                unset($_child[$key]['comment']);
                $_child[$key]['_child'] = [];
                $_child[$key]['phone'] = $value['phone'] != '' ? func::replace_phone($value['phone']) : $value['phone'];

                if($value['nickname'] != ''){
                    $_child[$key]['username'] = $value['nickname'];
                }else{
                    $_child[$key]['username'] = $value['phone'];
                }

                /*查找自己是否点赞*/
                $_child[$key]['islike'] = '0';
                $user = $this->getTokenUserId();
                if($user !='' && is_array($user)){
                    $islike = (new \yii\db\Query())->from(Like::$_tableName)->select('uid')->where(['uid'=>$user['id'],'comment_id'=>$value['comment_id'],'position_type'=>2,'catid'=>$catid])->one(); //查找自己是否已经点赞
                    if($islike && $islike['uid'] != ''){
                        $_child[$key]['islike'] = '1';
                    }
                }

                $comment_num = $this->find()->where('pid = '.$value['comment_id'].' and status =1')->count();
                $_child[$key]['comment'] = $comment_num;
            }
            //调整结构
            //
            $_child = $this->getTree($_child, $pid);
            foreach($_child as $value){
                $_child_data[$value['comment_id']] = $value['_child'];
            }
            //调整结构
        }

        foreach($data as $key=>$value){
            $data[$key]['_child'] = isset($_child_data[$value['comment_id']]) ? $_child_data[$value['comment_id']] : [];
            $data[$key]['phone'] = $value['phone'] != '' ? func::replace_phone($value['phone']) : $value['phone'];

            if($value['nickname'] != ''){
                $data[$key]['username'] = $value['nickname'];
            }else{
                $data[$key]['username'] = $value['phone'];
            }

            /*查找自己是否点赞*/
            $data[$key]['islike'] = '0';
            $user = $this->getTokenUserId();
            if($user !='' && is_array($user)){
                $islike = (new \yii\db\Query())->from(Like::$_tableName)->select('uid')->where(['uid'=>$user['id'],'comment_id'=>$value['comment_id'],'position_type'=>2,'catid'=>$catid])->one(); //查找自己是否已经点赞
                if($islike && $islike['uid'] != ''){
                    $data[$key]['islike'] = '1';
                }
            }
            /*查找自己是否点赞*/

            $comment_num = $this->find()->where('pid = '.$value['comment_id'].' and status =1')->count();
            $data[$key]['comment'] = $comment_num;
        }



        if($pid != 0){
            $query =(new \yii\db\Query());
            $query->from(self::tableName().' as a');
            $query->select('a.*,b.head_img,b.username,b.nickname,b.phone');
            $query->leftJoin('{{%user_app}} as b','a.uid = b.id');
            $query->where('a.`status` =1 and a.content_id='.$content_id.' and a.comment_id='.$pid);
            $p_data = $query->all();
            if(count($p_data) == 0){
                throw new HttpException(401,'未找到信息!',0);
            }
            $p_data = $p_data[0];
            $p_data['comment'] = count($data);
            $p_data['phone'] = $p_data['phone'] != '' ? func::replace_phone($p_data['phone']) : $p_data['phone'];

            if($p_data['nickname'] != ''){
                $p_data['username'] = $p_data['nickname'];
            }else{
                $p_data['username'] = $p_data['phone'];
            }

            $p_data['islike'] = '0';
            $user = $this->getTokenUserId();
            if($user !='' && is_array($user)){
                $islike = (new \yii\db\Query())->from(Like::$_tableName)->select('uid')->where(['uid'=>$user['id'],'comment_id'=>$p_data['comment_id'],'position_type'=>2,'catid'=>$catid])->one(); //查找自己是否已经点赞
                if($islike && $islike['uid'] != ''){
                    $p_data['islike'] = '1';
                }
            }

            /*查找点赞人*/
            $likes = (new \yii\db\Query())
                ->from(Like::$_tableName.' as a')
                ->leftJoin('{{%user_app}} as b','a.uid = b.id')
                ->select('a.*,b.head_img,b.username,b.nickname,b.phone')
                ->where(['comment_id'=>$pid,'position_type'=>2,'catid'=>$catid])
                ->limit(10)
                ->all();
            foreach($likes as $key=>$value){
                $phone = func::replace_phone($p_data['phone']);
                $likes[$key]['phone'] = $phone;
                $likes[$key]['nickname'] = $value['nickname'] != '' ? $value['nickname'] : $phone;
            }

            /*查找点赞人*/
            $parent = $p_data;
            $parent['_likes'] = $likes;

        }

        $_data = [];
        $_data['items']['parent'] = $parent;
        $_data['items']['_child'] = $data;
        $_data['_links'] = $this->linksEnvelope;
        $_data['_meta'] = $this->metaEnvelope;
        return $_data;
    }

    public function getTree($data, $pId)
    {
        $tree = [];
        foreach($data as $k => $v)
        {
            if($v['pid'] == $pId)
            {         //父亲找到儿子
                $v['_child'] = $this->getTree($data, $v['comment_id']);
                $tree[] = $v;
                //unset($data[$k]);
            }
        }
        return $tree;
    }

    /*
     * 统计系统推送
     * @param int $is_canel
     * @throws NotFoundHttpException
     */
    public function PushTj($content_id,$catid,$pid=0){
        try{
            $news_data = News::getInfoSim($content_id,$catid);
            if($news_data['thirdid'] =='' || $news_data['thirdid'] == 0) return true;
            $user = func::IdToUser($news_data['thirdid']) ;
            $nickname = $user->nickname != '' ? $user->nickname :func::replace_phone($user->phone);
            $phone = $user->phone;
            $data = '{"User_id":'.Yii::$app->user->identity->id.',"Article_id":'.$content_id.',"Article_type":'.$catid.',"Comment_time":"'.date('Y-m-d H:i:s').'","Article_title":"'.$news_data['title'].'","Nickname":"'.$nickname.'","Phone":'.$phone.'}';
            $data = array('data' => $data,'key'=>'c3RhdGlzdGlj');
            $json = func::GoCurl('/api/comment/insert',  'POST',$data, $error_msg);
            $array = json_decode($json, true);
            if($array['Code'] != 10000){

            }
        }catch (Exception $e){}
    }
}
